package model.DAO;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MySqlConnection {
	
	protected static final MySqlConnection msc = new MySqlConnection();
	
	protected Connection con;
	protected Statement st;
	protected ResultSet rs;
	private ArrayList<Map<String, String>> resultArray = new ArrayList<Map<String,String>>();
	private String url = "jdbc:mysql://localhost:3306/studyflow";
	private String user = "root";
	private String password = "";
      
	protected MySqlConnection(){
		try {
            con = DriverManager.getConnection(url, user, password);
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(MySqlDAOKerntaak.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } 
	}
	
	public static MySqlConnection getInstance(){
		return msc;
	}
	
	public void execute(String query){
		try {
			st = con.createStatement();
			rs = st.executeQuery(query);
			java.sql.ResultSetMetaData rsmd = (java.sql.ResultSetMetaData) rs.getMetaData();
			int c = 0;
			while(rs.next()){
				resultArray.add(c, new HashMap());
				for(int i = 0; i < rsmd.getColumnCount(); i++){
					resultArray.get(c).put(rsmd.getColumnName(i), rs.getString(i));
				}
				c++;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(MySqlDAOKerntaak.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
	}

	public ArrayList<Map<String, String>> getResultArray() {
		return resultArray;
	}
}
